package jnpf.message.service.impl.open;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.base.service.SysconfigService;
import jnpf.constant.MsgCode;
import jnpf.constant.PermissionConst;
import jnpf.message.model.message.OpenBaseModel;
import jnpf.message.model.message.OpenDeptModel;
import jnpf.message.model.message.OpenUserModel;
import jnpf.message.service.SynThirdInfoService;
import jnpf.message.service.ThirdOpenService;
import jnpf.message.util.SynThirdConsts;
import jnpf.model.BaseSystemInfo;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.entity.UserRelationEntity;
import jnpf.permission.service.OrganizeService;
import jnpf.permission.service.UserRelationService;
import jnpf.permission.service.UserService;
import jnpf.util.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static jnpf.message.model.message.OpenBaseModel.OperationType.DISABLE;

@Service
@Log4j2
@RequiredArgsConstructor
public class ThirdOpenUserServiceImpl implements ThirdOpenService {

	private final SynThirdInfoService synThirdInfoService;

	private final OrganizeService organizeService;

	private final UserProvider userProvider;

	private final UserService userService;

	private final SysconfigService sysconfigService;

	private final UserRelationService userRelationService;

	private final RedisUtil redisUtil;

	private final CacheKeyUtil cacheKeyUtil;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Object beforeProcess(OpenBaseModel openBaseModel, Map<String, OpenDeptModel> organizeMap) {
		OpenUserModel openUserModel = (OpenUserModel) openBaseModel;
		OpenBaseModel.OperationType operationType = openUserModel.getType();
		String description = "";
		BaseSystemInfo sysInfo = sysconfigService.getSysInfo();
		try {
			switch (operationType) {
				case ADD:
				case EDIT:
				case ENABLE:
				case DISABLE:
					// 检测账户唯一
					UserEntity userEntity = userService.getUserByMobile(openUserModel.getMobile());
					if (Objects.isNull(userEntity)) {
						userEntity = new UserEntity();
					}
					if (StringUtil.isEmpty(openUserModel.getMobile())) {
						description = MsgCode.PS007.get();
						break;
					}
					if (StringUtil.isEmpty(openUserModel.getName())) {
						description = MsgCode.PS008.get();
						break;
					}
					//判断中间表用户组织是否存在
					userEntity.setId(openUserModel.getUserid());
					userEntity.setAccount(openUserModel.getMobile());
					userEntity.setEmail(openUserModel.getEmail());
					userEntity.setCertificatesNumber(openUserModel.getIdCard());
					userEntity.setMobilePhone(openUserModel.getMobile());
					userEntity.setRealName(openUserModel.getName());
					userEntity.setEnabledMark(operationType == DISABLE ? 0 : 1);
					userEntity.setOrganizeId(Optional.ofNullable(openUserModel.getDeptIdList()).orElse(new ArrayList<>()).stream().distinct().collect(Collectors.joining(",")));
					userEntity.setPositionId(Optional.ofNullable(openUserModel.getPositionIdList()).orElse(new ArrayList<>()).stream().distinct().collect(Collectors.joining(",")));
					userEntity.setRoleId(Optional.ofNullable(openUserModel.getRoleIdList()).orElse(new ArrayList<>()).stream().distinct().collect(Collectors.joining(",")));
					String secretkey = RandomUtil.uuId();
					userEntity.setPassword(Md5Util.getStringMd5(sysInfo.getNewUserDefaultPassword().toLowerCase() + secretkey.toLowerCase()));
					userEntity.setSecretkey(secretkey);
					userEntity.setIsAdministrator(0);
					userEntity.setHeadIcon("001.png");
					userEntity.setGender("3");
//					userEntity.setQuickQuery(PinYinUtil.getFirstSpell(userEntity.getRealName()));
					return userEntity;
				case DELETE:
					UserEntity entity = userService.getInfo(openUserModel.getUserid());
					//判断是否是部门主管
					if (organizeService.getList(false).stream().filter(t -> openUserModel.getUserid().equals(t.getManagerId())).collect(Collectors.toList()).size() > 0) {
						description = MsgCode.PS027.get();
						break;
					}
					// 有下属不允许删除
					if (userService.getListByManagerId(openUserModel.getUserid(), null).size() > 0) {
						description = MsgCode.PS028.get();
						break;
					}
					userService.delete(entity);
					userService.delCurUser(MsgCode.PS010.get(), entity.getId());
			}
		} catch (Exception e) {
			description = e.getMessage();
			e.printStackTrace();
			throw e;
		} finally {
			saveSynThirdInfoEntity(operationType, SynThirdConsts.DATA_TYPE_USER, openUserModel.getUserid(), StringUtils.isBlank(description) ? 2 : 1, description, synThirdInfoService, userProvider);
		}
		return null;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void afterProcess(List<Object> result) {
		List<UserEntity> entityList = result.stream().map(e -> (UserEntity) e).filter(Objects::nonNull).collect(Collectors.toList());
		Set<String> userIds = entityList.stream().filter(e -> StringUtils.isNotBlank(e.getId())).map(UserEntity::getId).collect(Collectors.toSet());

		userService.saveOrUpdateBatch(entityList);
		List<UserRelationEntity> userRelationEntities = entityList.stream().map(e -> {
			return getRelationList(e);
		}).flatMap(e -> e.stream()).collect(Collectors.toList());
		if (CollectionUtil.isNotEmpty(userIds)) {
			QueryWrapper<UserRelationEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().in(UserRelationEntity::getUserId, userIds);
			queryWrapper.lambda().ne(UserRelationEntity::getObjectType, PermissionConst.GROUP);
			userRelationService.remove(queryWrapper);
		}
		if (CollectionUtil.isNotEmpty(userRelationEntities)) {
			userRelationService.saveBatch(userRelationEntities);
		}
		//清理获取所有用户的redis缓存
		redisUtil.remove(cacheKeyUtil.getAllUser());
	}

	private List<UserRelationEntity> getRelationList(UserEntity entity) {
		List<String> userAllOrgIds = Arrays.asList(entity.getOrganizeId().split(","));
		List<String> userAllPosIds = StringUtil.isNotEmpty(entity.getPositionId()) ? Arrays.asList(entity.getPositionId().split(",")) : new ArrayList<>();
		List<String> userAllRoleIds = StringUtil.isNotEmpty(entity.getRoleId()) ? Arrays.asList(entity.getRoleId().split(",")) : new ArrayList<>();
		// 更新用户关系（组织/岗位/角色）
		List<UserRelationEntity> relationList = new ArrayList<>();
		setUserRelation(relationList, PermissionConst.ORGANIZE, userAllOrgIds, entity);
		setUserRelation(relationList, PermissionConst.POSITION, userAllPosIds, entity);
		setUserRelation(relationList, PermissionConst.ROLE, userAllRoleIds, entity);
		return relationList;
	}

	/**
	 * 设置用户关联对象
	 */
	private void setUserRelation(List<UserRelationEntity> relationList, String objectType, List<String> ids, UserEntity userEntity) {
		for (String id : ids) {
			UserRelationEntity relationEntity = new UserRelationEntity();
			relationEntity.setId(RandomUtil.uuId());
			relationEntity.setObjectType(objectType);
			relationEntity.setObjectId(id);
			relationEntity.setUserId(userEntity.getId());
			relationEntity.setCreatorTime(userEntity.getCreatorTime());
			relationEntity.setCreatorUserId(userEntity.getCreatorUserId());
			relationList.add(relationEntity);
		}
	}


}
